package com.itdaan.portal.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author www.itdaan.com
 */
public class JspToHtmlUtil {

	/**
	 * 根据本地模板生成静态页面
	 * 
	 * @param JspFile
	 *            jsp路经
	 * @param HtmlFile
	 *            html路经
	 * @return
	 */
	public static boolean JspToHtmlFile(String fileUrl, String HtmlFile) {
		String str = "";
		str = getHtmlTextByURL(fileUrl).toString();
		if(str.isEmpty()){
			return false;
		}
		BufferedWriter o = null;
		OutputStreamWriter osw = null;
		FileOutputStream fos = null;
		try {
			File f = new File(HtmlFile);
			fos = new FileOutputStream(f);
			osw = new OutputStreamWriter(fos,"UTF-8");
			o = new BufferedWriter(osw);
			o.write(str);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally{
			if(o != null){
				try {
					o.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				o = null;
			}
			if(osw != null){
				try {
					osw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				osw = null;
			}if(fos != null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				fos = null;
			}
		}
		return true;
	}

	/**
	 * 根据url生成静态页面
	 * 
	 * @param url
	 * @return d
	 */
	public static StringBuffer getHtmlTextByURL(String url) {
		StringBuffer sb = new StringBuffer();
		String nextLine = null;
		URLConnection uc = null;
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			URL u = new URL(url);
			uc = u.openConnection();
			uc.setReadTimeout(5000);
			is = uc.getInputStream();
			isr = new InputStreamReader(is,"UTF-8");
			br = new BufferedReader(isr);
			while ((nextLine = br.readLine()) != null) {
				sb.append(nextLine);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return sb;
		} finally{
			if(uc != null){
				uc = null;
			}
			if(is != null){
				try {
					is.close();
					is = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(isr != null){
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				isr = null;
			}
		}
		return sb;
	}
	
	public static void main(String[] args) {
		JspToHtmlFile("http://www.itdaan.com/post-1-10001.html","D:\\ddd1.html");
	}
}
